package com.block.source.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.model.vo.CheckUserVO;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.LogFactory;
import com.block.datapush.special.service.IDataPushSourceSpecialService;
import com.block.db.entity.*;
import com.block.db.mapper.MemberInfoMapper;
import com.block.db.mapper.SourceRecordInfoMapper;
import com.block.db.model.param.SpeItemInfoParam;
import com.block.source.enums.DataActionEnum;
import com.block.source.enums.FlowTypeEnum;
import com.block.source.service.ISourceDataAddupService;
import com.block.source.service.ISourceHandleCheckUserService;
import com.block.source.service.ISourceRecordInfoService;
import com.block.source.service.ISourceTaskInfoService;
import com.block.test.reqbean.source.CheckUserInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

@Service
public class SourceHandleCheckUserServiceImpl implements ISourceHandleCheckUserService {

    private static Logger log = LogFactory.getSourceLog();

    @Resource
    MemberInfoMapper memberInfoMapper;
    @Autowired
    TransactionTemplate transactionTemplate;
    @Autowired
    ISourceTaskInfoService sourceTaskInfoService;
    @Autowired
    IDataPushSourceSpecialService dataPushSpecialService3;
    @Autowired
    ISourceRecordInfoService sourceRecordInfoService;
    @Resource
    SourceRecordInfoMapper sourceRecordInfoMapper;
    @Autowired
    ISourceDataAddupService sourceDataAddupService;

    @Override
    public ResultInfoVO handleCheckUserInfo(SourceBaseInfo sourceBaseInfo, CheckUserInfo checkUserInfo) {

        String mobileMd5 = checkUserInfo.getMobileMd5().toLowerCase(Locale.ROOT);
        checkUserInfo.setMobileMd5(mobileMd5);

        String dateInfo = LocalDate.now().toString();

        // 查询订单号是否已经存在
        SourceRecordInfo sourceRecordInfo =
                sourceRecordInfoMapper.getEntityByInfoIdAndOrderNo(sourceBaseInfo.getId(), checkUserInfo.getOrderNo());
        if (ObjectUtil.isNotEmpty(sourceRecordInfo)){
            // 订单号重复
            log.info("【前置检测】订单号重复【orderNo】{}", checkUserInfo.getOrderNo());
            return ResultInfoVO.error("订单号重复");
        }

        // 检测数据是否已经入库
        MemberInfo memberInfo = memberInfoMapper.getMemberInfoByMobileMd5(checkUserInfo.getMobileMd5());
        // 构造返回数据
        CheckUserVO checkUserVO = new CheckUserVO();
        checkUserVO.setCanPush(false);
        checkUserVO.setMobileMd5(mobileMd5);
        if (ObjectUtil.isNotEmpty(memberInfo)){
            sourceDataAddupService.saveOrUpdateDataAddupInfo(dateInfo, DataActionEnum.CHECK, sourceBaseInfo,  null);
            log.info("【前置检测】用户已经存在【uid】{}【mobileMd5】{}", memberInfo.getUid(), checkUserInfo.getMobileMd5());
            return ResultInfoVO.success(checkUserVO.toJsonObject());
        }

        // 获取可用的推送任务信息
        SourceTaskInfo taskInfo = sourceTaskInfoService.getEnableEntityOne(sourceBaseInfo.getId(), checkUserInfo);
        if (ObjectUtil.isEmpty(taskInfo)){
            sourceDataAddupService.saveOrUpdateDataAddupInfo(dateInfo, DataActionEnum.CHECK, sourceBaseInfo,  null);
            log.info("【前置检测】推送任务不可用【sourceId】{}", sourceBaseInfo.getId());
            return ResultInfoVO.error("没有符合条件的推送任务");
        }

        // 保存历史信息
        SourceRecordInfo recordInfo = sourceRecordInfoService.recordDataInfo(taskInfo, checkUserInfo);
        if (ObjectUtil.isEmpty(recordInfo)){
            sourceDataAddupService.saveOrUpdateDataAddupInfo(dateInfo, DataActionEnum.CHECK, sourceBaseInfo,  null);
            log.info("【前置检测】入库资质信息失败");
            return ResultInfoVO.error("信息入库失败");
        }

        /**
         * 线索数据全量接收
         */
        if (ObjectUtil.equals(sourceBaseInfo.getFlowType(), FlowTypeEnum.ALL.getValue())){
            // 全量推送，不进行机构条件的匹配
            // 统计可以推送信息
            sourceDataAddupService.saveOrUpdateDataAddupInfo(dateInfo, DataActionEnum.CANPUSH, sourceBaseInfo,  null);
            checkUserVO.setCanPush(true);
            checkUserVO.setTradeNo(String.valueOf(recordInfo.getId()));
            return ResultInfoVO.success(checkUserVO.toJsonObject());
        }

        // 根据线索撞库信息，生成临时 memberExtInfo 信息
        MemberExtInfo memberExtInfo = sourceRecordInfoService.getExtInfoByRecordInfo(recordInfo);

        /**
         * 根据线索信息进行撞库
         * 获取可推送的任务列表
         */
        SpeItemInfoParam speItemInfoParam = new SpeItemInfoParam();
        speItemInfoParam.setPriceAmount(recordInfo.getPriceAmount());
        List<SpecialCostomItemInfo> itemInfoList = dataPushSpecialService3.dataCheckHandle(memberExtInfo, speItemInfoParam);

        if (CollUtil.isNotEmpty(itemInfoList)){

            // 有推送机构信息，则更新相关记录信息，并返回该订单可推送
            List<Long> collect = itemInfoList.stream().map(itemInfo -> itemInfo.getInfoId()).collect(Collectors.toList());
            SourceRecordInfo updateEntity = new SourceRecordInfo();
            updateEntity.setId(recordInfo.getId());
            updateEntity.setSpeInfoIdArr(JSON.toJSONString(collect));
            sourceRecordInfoService.updateById(updateEntity);

            // 统计可以推送信息
            sourceDataAddupService.saveOrUpdateDataAddupInfo(dateInfo, DataActionEnum.CANPUSH, sourceBaseInfo,  null);

            // 根据记录信息检测生成用户扩展信息对象
            checkUserVO.setCanPush(true);
            checkUserVO.setTradeNo(String.valueOf(recordInfo.getId()));
            return ResultInfoVO.success(checkUserVO.toJsonObject());
        }else{
            SourceRecordInfo updateEntity = new SourceRecordInfo();
            updateEntity.setId(recordInfo.getId());
            updateEntity.setStatus(-1);
            updateEntity.setMessage("无推送机构信息");
            sourceRecordInfoService.updateById(updateEntity);

            // 统计可以推送信息
            sourceDataAddupService.saveOrUpdateDataAddupInfo(dateInfo, DataActionEnum.CHECK, sourceBaseInfo,  null);

            // 根据记录信息检测生成用户扩展信息对象
            checkUserVO.setCanPush(false);
            return ResultInfoVO.success(checkUserVO.toJsonObject());
        }
    }

}
